package utils

import (
	"crypto/rand"
	"crypto/rsa"
	"crypto/x509"
	"encoding/base64"
	"encoding/json"
	"encoding/pem"
)

var pubkeyStr string
var privkeyStr string

var pubkey *rsa.PublicKey
var privkey *rsa.PrivateKey

func init() {
	var err error
	pubkeyStr = Config.Section("crypto").Key("pubkey").String()
	privkeyStr = Config.Section("crypto").Key("privkey").String()
	pbk := []byte("-----BEGIN PUBLIC KEY-----\n" + pubkeyStr + "\n-----END PUBLIC KEY-----")
	pvk := []byte("-----BEGIN RSA PRIVATE KEY-----\n" + privkeyStr + "\n-----END RSA PRIVATE KEY-----")

	var pubkeyI interface{}
	pubBlock, _ := pem.Decode(pbk)
	if pubBlock == nil {
		panic("public key error!")
	}
	pubkeyI, err = x509.ParsePKIXPublicKey(pubBlock.Bytes)
	if err != nil {
		panic("public key error: " + err.Error())
	}
	pubkey = pubkeyI.(*rsa.PublicKey)

	privBlock, _ := pem.Decode(pvk)
	if privBlock == nil {
		panic("private key error!")
	}
	privkey, err = x509.ParsePKCS1PrivateKey(privBlock.Bytes)
	if err != nil {
		panic("private key error: " + err.Error())
	}
}

// 默认加密
func RsaEncrypt(origData []byte) ([]byte, error) {
	return rsa.EncryptPKCS1v15(rand.Reader, pubkey, origData)
}

// 默认解密
func RsaDecrypt(ciphertext []byte) ([]byte, error) {
	return rsa.DecryptPKCS1v15(rand.Reader, privkey, ciphertext)
}

// Base64解密, Rsa解密, Json序列化
func B64RsaJsonDecrypt(str string, v interface{}) error {
	datab, err := base64.StdEncoding.DecodeString(str)
	if err != nil {
		return err
	}
	jsdatab, err := rsa.DecryptPKCS1v15(rand.Reader, privkey, []byte(datab))
	if err != nil {
		return err
	}
	// fmt.Println(string(jsdatab))
	err = json.Unmarshal(jsdatab, v)
	if err != nil {
		return err
	}
	return nil
}

func GetPubKeyString() string {
	return pubkeyStr
}
